/**
 * 信任状态过渡管理器
 * 管理信任卡牌的状态过渡动画和效果
 */

class TrustTransitionManager {
  constructor() {
    this.transitionQueue = []
    this.isProcessing = false
    this.transitionDuration = 1000
  }

  /**
   * 添加信任变化过渡
   */
  addTrustTransition(cardId, oldValue, newValue, reason = '信任变化') {
    const transition = {
      id: Date.now(),
      cardId,
      oldValue,
      newValue,
      change: newValue - oldValue,
      reason,
      timestamp: new Date().toISOString(),
      status: 'pending'
    }

    this.transitionQueue.push(transition)
    this.processTransitions()

    return transition.id
  }

  /**
   * 处理过渡队列
   */
  async processTransitions() {
    if (this.isProcessing || this.transitionQueue.length === 0) return

    this.isProcessing = true

    while (this.transitionQueue.length > 0) {
      const transition = this.transitionQueue.shift()
      await this.executeTransition(transition)
    }

    this.isProcessing = false
  }

  /**
   * 执行单个过渡
   */
  async executeTransition(transition) {
    return new Promise((resolve) => {
      transition.status = 'processing'

      // 触发过渡开始事件
      this.emitTransitionEvent('start', transition)

      // 计算过渡步骤
      const steps = this.calculateTransitionSteps(transition)
      let currentStep = 0

      const stepInterval = setInterval(() => {
        if (currentStep >= steps.length) {
          clearInterval(stepInterval)
          transition.status = 'completed'
          this.emitTransitionEvent('complete', transition)
          resolve()
          return
        }

        const step = steps[currentStep]
        this.emitTransitionEvent('step', { ...transition, step })
        currentStep++
      }, this.transitionDuration / steps.length)
    })
  }

  /**
   * 计算过渡步骤
   */
  calculateTransitionSteps(transition) {
    const { oldValue, newValue, change } = transition
    const steps = []
    const stepCount = Math.min(20, Math.abs(change))
    const stepSize = change / stepCount

    for (let i = 0; i <= stepCount; i++) {
      const value = oldValue + (stepSize * i)
      const progress = i / stepCount

      steps.push({
        value: Math.round(value),
        progress,
        isFinal: i === stepCount
      })
    }

    return steps
  }

  /**
   * 获取过渡效果配置
   */
  getTransitionEffect(transition) {
    const { change, newValue } = transition
    const effects = []

    // 基础过渡效果
    if (change > 0) {
      effects.push({
        type: 'positive',
        intensity: Math.min(1, Math.abs(change) / 50),
        duration: this.transitionDuration
      })
    } else if (change < 0) {
      effects.push({
        type: 'negative',
        intensity: Math.min(1, Math.abs(change) / 50),
        duration: this.transitionDuration
      })
    }

    // 特殊效果
    if (newValue >= 100) {
      effects.push({
        type: 'max_trust',
        intensity: 1,
        duration: 2000
      })
    }

    if (newValue <= 0) {
      effects.push({
        type: 'broken_trust',
        intensity: 1,
        duration: 2000
      })
    }

    if (newValue >= 80 && transition.oldValue < 80) {
      effects.push({
        type: 'high_trust_achieved',
        intensity: 1,
        duration: 1500
      })
    }

    if (newValue < 20 && transition.oldValue >= 20) {
      effects.push({
        type: 'low_trust_warning',
        intensity: 1,
        duration: 1500
      })
    }

    return effects
  }

  /**
   * 获取过渡动画配置
   */
  getTransitionAnimation(transition) {
    const { change, newValue } = transition
    const animations = []

    // 基础动画
    if (change > 0) {
      animations.push({
        name: 'trustIncrease',
        duration: this.transitionDuration,
        easing: 'ease-out'
      })
    } else if (change < 0) {
      animations.push({
        name: 'trustDecrease',
        duration: this.transitionDuration,
        easing: 'ease-in'
      })
    }

    // 特殊动画
    if (newValue >= 100) {
      animations.push({
        name: 'maxTrustGlow',
        duration: 2000,
        easing: 'ease-in-out'
      })
    }

    if (newValue <= 0) {
      animations.push({
        name: 'brokenTrustShake',
        duration: 1000,
        easing: 'ease-in-out'
      })
    }

    return animations
  }

  /**
   * 获取过渡颜色
   */
  getTransitionColor(trustValue) {
    if (trustValue >= 80) return '#4caf50'
    if (trustValue >= 50) return '#ff9800'
    if (trustValue >= 20) return '#ff5722'
    return '#f44336'
  }

  /**
   * 获取过渡文本
   */
  getTransitionText(transition) {
    const { change, newValue } = transition

    if (change > 0) {
      return `信任值 +${change}`
    } else if (change < 0) {
      return `信任值 ${change}`
    }

    return '信任值不变'
  }

  /**
   * 获取过渡图标
   */
  getTransitionIcon(transition) {
    const { change, newValue } = transition

    if (newValue >= 100) return '💎'
    if (newValue <= 0) return '💔'
    if (change > 0) return '📈'
    if (change < 0) return '📉'
    return '⚖️'
  }

  /**
   * 触发过渡事件
   */
  emitTransitionEvent(eventType, data) {
    // 这里可以触发自定义事件或调用回调函数
    if (typeof window !== 'undefined' && window.dispatchEvent) {
      const event = new CustomEvent('trustTransition', {
        detail: { eventType, data }
      })
      window.dispatchEvent(event)
    }
  }

  /**
   * 清除所有过渡
   */
  clearAllTransitions() {
    this.transitionQueue = []
    this.isProcessing = false
  }

  /**
   * 获取过渡统计
   */
  getTransitionStats() {
    return {
      queueLength: this.transitionQueue.length,
      isProcessing: this.isProcessing,
      totalProcessed: this.transitionQueue.filter(t => t.status === 'completed').length
    }
  }

  /**
   * 设置过渡持续时间
   */
  setTransitionDuration(duration) {
    this.transitionDuration = Math.max(100, Math.min(5000, duration))
  }

  /**
   * 暂停过渡处理
   */
  pauseTransitions() {
    this.isProcessing = false
  }

  /**
   * 恢复过渡处理
   */
  resumeTransitions() {
    this.processTransitions()
  }
}

// 创建单例实例
const trustTransitionManager = new TrustTransitionManager()

export default trustTransitionManager

